package com.zeta.plan.service.impl;

import com.zeta.plan.exception.AuthenticationException;
import com.zeta.plan.exception.DuplicationUsernameException;
import com.zeta.plan.mapper.UserMapper;
import com.zeta.plan.model.dto.UserDTO;
import com.zeta.plan.model.entity.UserDO;
import com.zeta.plan.service.UserService;
import com.zeta.plan.utils.RandomString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    public Long addUser(UserDO userDO) {
        // 判断 username 是否重复
        UserDO userDO1 = userMapper.getUserByUsername(userDO.getUsername());
        if (userDO1 != null) { //重复
            throw new DuplicationUsernameException("用户名重复");
        }
        return userMapper.insertUser(userDO);
    }

    @Override
    public UserDO findUserByUsernameAndPassword(String username, String password) {
        UserDO userDO = userMapper.getUserByUsernameAndPassword(username, password);
        return userDO;
    }

    @Override
    public void deleteUserByUsername(String username) {
        userMapper.deleteUserByUsername(username);
    }

    @Override
    public String findSecretByUsername(String username) {
        return userMapper.findSecretByUsername(username);
    }

    @Override
    public boolean findEnabledByUsername(String username) {
        return userMapper.findEnabledByUsername(username);
    }

    @Override
    public boolean updateEnabledByUsername(String username, boolean enabled) {
        // 修改之前先查询一次
        if (userMapper.findEnabledByUsername(username) == enabled) {
            return true;
        }
        return userMapper.updateEnabledByUsername(username, enabled) > 0;
    }

    @Override
    public UserDO findUserById(Long id) {
        return userMapper.findUserById(id);
    }

    @Override
    public String findSaltByUsername(String username) {
        return userMapper.findSaltByUsername(username);
    }

    @Override
    public boolean updateSecretByID(Long id, String secret) {
        return userMapper.updateSecretByID(id, secret) > 0;
    }

    @Override
    public boolean updatePasswordByUsernameAndPassword(String username, String oldPassword, String newPassword) {
        return userMapper.updatePasswordByUsernameAndPassword(username, oldPassword, newPassword) > 0;
    }

    @Override
    public boolean updateUserInfoById(UserDTO userDTO) {
        return userMapper.updateUserInfoById(userDTO) > 0;
    }
}
